﻿package com.thorqq.magictimer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import com.baidu.mobstat.StatService;
import com.thorqq.magictimer.action.ActionMgr;
import com.thorqq.magictimer.core.ChildView;
import com.thorqq.magictimer.core.ChildViewParent;
import com.thorqq.magictimer.core.TAction;
import com.thorqq.magictimer.core.TLoopPolicy;
import com.thorqq.magictimer.core.TTimerDef;
import com.thorqq.magictimer.db.DBHelper;
import com.thorqq.magictimer.timeLoop.ChildViewLoopDay;
import com.thorqq.magictimer.timeLoop.ChildViewLoopDayNDays;
import com.thorqq.magictimer.timeLoop.ChildViewLoopMonDay;
import com.thorqq.magictimer.timeLoop.ChildViewLoopMonWeek;
import com.thorqq.magictimer.timeLoop.ChildViewLoopWeek;
import com.thorqq.magictimer.timeLoop.ChildViewTimeDef;
import com.thorqq.magictimer.timeLoop.TLoopPolicyMon;
import com.thorqq.magictimer.timeLoop.Timer;
import com.thorqq.magictimer.timeLoop.TimerMgr;
import com.thorqq.magictimer.util.Util;
import com.thorqq.magictimer.widget.ListViewNoScroll;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class SettingActivityTimer extends ChildViewParent /*implements ChildViewParent*/
{
    public static final int REQUEST_CODE_TIME_SETTING = 1;
    public static final int REQUEST_CODE_LOOP_SETTING = 2;
    public static final int REQUEST_CODE_ACTION_SETTING = 3;
    public static final int REQUEST_CODE_LOOP_NEW = 4;
    public static final int REQUEST_CODE_ACTION_NEW = 5;

    public static final int REQUEST_CODE_LOOP_CHANGE = 6;
    public static final int REQUEST_CODE_ACTION_CHANGE = 7;

    private Timer mTimer;
    private ScrollView mScrollView;

    //time & name
    private ArrayList<Map<String, Object>> mTimeDefList = new ArrayList<Map<String, Object>>();
    private AdapterTimeDef mTimeDefAdapter;
    private ListViewNoScroll mTimeDefListView;
    private View mTimeDefItemHeader;

    //policy
    private Button mBtnAddLoopPolicy;
    private ArrayList<Map<String, Object>> mLoopPolicyList = new ArrayList<Map<String, Object>>();
    private AdapterLoopPolicy mLoopPolicyAdapter;
    private ListViewNoScroll mLoopPolicyListView;
    private View mPolicyItemHeader;

    //action
    private Button mBtnAddAction;
    private ArrayList<Map<String, Object>> mActionList = new ArrayList<Map<String, Object>>();
    private AdapterAction mActionAdapter;
    private ListViewNoScroll mActionListView;
    private View mActionItemHeader;

    private TextView mTvNoLoopPolicy;
    private TextView mTvNoAction;

    //save & cancel
    private Button mBtnSave;
    private Button mBtnCancel;
    
    //policy上下文菜单
    private View mPolicyMenuView;
    private TextView mPolicyMenuInclude;
    private TextView mPolicyMenuDelete;
    private TextView mPolicyMenuChange;
    private PopupWindow mPolicyMenu;
    private final int mPolicyMenuHeight = 300;
    private int mCurrentPolicyPos;

    //action上下文菜单
    private View mActionMenuView;
    private TextView mActionMenuDelete;
    private TextView mActionMenuChange;
    private PopupWindow mActionMenu;
    private final int mActionMenuHeight = 200; //TODO 这里只能写死，不知道怎么动态获取高度
    private int mCurrentActionPos;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.timer_setting);

        mTimer = getIntent().getParcelableExtra(TimerMgr.ALARM_INTENT_EXTRA);
        if (mTimer == null)
        {
            Util.log("mTimer is null");
            return;
        }

        initLayout();
        updateLayout();
        registerListener();
    }
    
    private void initLayout()
    {
        mScrollView = (ScrollView)findViewById(R.id.scrollViewTimerSetting);
        
        //time
        mTimeDefListView = (ListViewNoScroll)findViewById(R.id.ListViewNoScrollTimeDef);
        mTimeDefAdapter = new AdapterTimeDef(this, mTimeDefList);
        mTimeDefListView.setAdapter(mTimeDefAdapter);
        mTimeDefListView.setDivider(this.getResources().getDrawable(R.drawable.gradient_shape_hor));
        mTimeDefListView.setDividerHeight(1);
        
        mTimeDefItemHeader = getLayoutInflater().inflate(R.layout.timedef_item_header, null);
        mTimeDefListView.addHeaderView(mTimeDefItemHeader);
                
        //循环策略
        mLoopPolicyListView = (ListViewNoScroll)findViewById(R.id.ListViewNoScrollLoopPolicy);
        mLoopPolicyAdapter = new AdapterLoopPolicy(this, mLoopPolicyList);
        mLoopPolicyListView.setAdapter(mLoopPolicyAdapter);
        mLoopPolicyListView.setDivider(this.getResources().getDrawable(R.drawable.gradient_shape_hor));
        mLoopPolicyListView.setDividerHeight(1);
        
        mPolicyItemHeader = getLayoutInflater().inflate(R.layout.loop_item_header, null);
        mLoopPolicyListView.addHeaderView(mPolicyItemHeader);
        mBtnAddLoopPolicy = (Button) mPolicyItemHeader.findViewById(R.id.btnAddLoopPolicy);

        mTvNoLoopPolicy = (TextView)findViewById(R.id.tvNoLoopPolicy);
        mLoopPolicyListView.setEmptyView(mTvNoLoopPolicy);

        //定时动作
        mActionListView = (ListViewNoScroll)findViewById(R.id.ListViewNoScrollAction);
        mActionAdapter = new AdapterAction(this, mActionList);
        mActionListView.setAdapter(mActionAdapter);
        mActionListView.setDivider(this.getResources().getDrawable(R.drawable.gradient_shape_hor));
        mActionListView.setDividerHeight(1);
        
        mActionItemHeader = getLayoutInflater().inflate(R.layout.action_item_header, null);
        mActionListView.addHeaderView(mActionItemHeader);
        mBtnAddAction = (Button) mActionItemHeader.findViewById(R.id.btnAddAction);
        
        mTvNoAction = (TextView)findViewById(R.id.tvNoAction);
        mActionListView.setEmptyView(mTvNoAction);

        //保存、取消
        mBtnSave = (Button) findViewById(R.id.btnSave);
        mBtnCancel = (Button) findViewById(R.id.btnCancel);
        
        //policy 上下文菜单
        mPolicyMenuView = getLayoutInflater().inflate(R.layout.menu_policy, null, false);
        mPolicyMenu = new PopupWindow(mPolicyMenuView, 
                LinearLayout.LayoutParams.WRAP_CONTENT, 
                LinearLayout.LayoutParams.WRAP_CONTENT,
                true);
        mPolicyMenuInclude = (TextView) mPolicyMenuView.findViewById(R.id.tvPolicyMenuInclude);
        mPolicyMenuDelete  = (TextView) mPolicyMenuView.findViewById(R.id.tvPolicyMenuDelete);
        mPolicyMenuChange  = (TextView) mPolicyMenuView.findViewById(R.id.tvPolicyMenuChange);

        //action 上下文菜单
        mActionMenuView = getLayoutInflater().inflate(R.layout.menu_action, null, false);
        mActionMenu = new PopupWindow(mActionMenuView, 
                LinearLayout.LayoutParams.WRAP_CONTENT, 
                LinearLayout.LayoutParams.WRAP_CONTENT,
                true);
        mActionMenuDelete = (TextView) mActionMenuView.findViewById(R.id.tvActionMenuDelete);
        mActionMenuChange = (TextView) mActionMenuView.findViewById(R.id.tvActionMenuChange);
    }
    
    private ChildView createChildViewPolicy(TLoopPolicy policy)
    {
        switch(policy.getPolicyType())
        {
        case TLoopPolicy.LOOP_POLICY_DAY: 
            return new ChildViewLoopDay(this, policy);
        case TLoopPolicy.LOOP_POLICY_DAY_NDAYS:
            return new ChildViewLoopDayNDays(this, policy);
        case TLoopPolicy.LOOP_POLICY_WEEK: 
            return new ChildViewLoopWeek(this, policy);
        case TLoopPolicy.LOOP_POLICY_MONTH: 
            TLoopPolicyMon monPolicy = (TLoopPolicyMon)policy;
            if(monPolicy.mSubLoopType == TLoopPolicyMon.MONTH_LOOP_SUB_LOOP_DAY)
            {
                return new ChildViewLoopMonDay(this, policy);
            }
            else if(monPolicy.mSubLoopType == TLoopPolicyMon.MONTH_LOOP_SUB_LOOP_WEEK)
            {
                return new ChildViewLoopMonWeek(this, policy);
            }
            break;
        default:
            return null;
        }
        return null;
    }
    
    //TTimerDef
    private HashMap<String, Object> makeMap(TTimerDef timedef)
    {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("timedef", timedef);
        map.put("listener", new TimeDefButtonListener());        
        map.put("childView", new ChildViewTimeDef(this, timedef));
        map.put("visibility", View.GONE);
        map.put("parent", this);
        map.put("scrollview", this.mScrollView);
        
        return map;
    }
    
    private void updateTimerDefLayout()
    {
        mTimeDefList.clear();
        mTimeDefList.add(this.makeMap(mTimer.getTimerDef()));
        mTimeDefAdapter.notifyDataSetChanged();        
    }
    
    private void updateTimerDefLayout(TTimerDef timeDef)
    {
        mTimeDefList.get(0).put("timedef", timeDef);

        mTimeDefAdapter.notifyDataSetChanged();        
    }
    
    //policy
    private HashMap<String, Object> makeMap(TLoopPolicy policy)
    {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("policy", policy);
        map.put("listener", new LoopPolicyButtonListener(this, policy));
        map.put("longListener", new LoopPolicyLongClickListener(this, policy));
        map.put("deleteListener", new LoopPolicyDeleteListener(this, policy));
        map.put("childView", createChildViewPolicy(policy));
        map.put("parent", this);
        map.put("visibility", View.GONE);
        map.put("scrollview", this.mScrollView);
        
        return map;
    }

    private void updatePolicyLayout()
    {
        // 循环策略
        mLoopPolicyList.clear();
        for (TLoopPolicy policy : mTimer.getLoopPolicys())
        {
            mLoopPolicyList.add(this.makeMap(policy));
        }

        mLoopPolicyAdapter.notifyDataSetChanged();        
    }
    
    private void updatePolicyLayout(TLoopPolicy policy)
    {
        int i = 0;
        for(; i < mLoopPolicyList.size(); i++)
        {
            TLoopPolicy p = (TLoopPolicy) mLoopPolicyList.get(i).get("policy");
            if(policy.getDisplayOrder() == p.getDisplayOrder())
            {
                mLoopPolicyList.get(i).put("policy", policy);
                mLoopPolicyAdapter.notifyDataSetChanged();        
                return;
            }
        }
        
        if(i == mLoopPolicyList.size())
        {
            updatePolicyLayout();
        }

    }
    
    private void updatePolicyLayout(TLoopPolicy policy, ChildView view)
    {
        int i = 0;
        for(; i < mLoopPolicyList.size(); i++)
        {
            TLoopPolicy p = (TLoopPolicy) mLoopPolicyList.get(i).get("policy");
            if(policy.getDisplayOrder() == p.getDisplayOrder())
            {
                mLoopPolicyList.get(i).put("policy", policy);
                mLoopPolicyList.get(i).put("childView", view);
                mLoopPolicyAdapter.notifyDataSetChanged();        
                return;
            }
        }
        
        if(i == mLoopPolicyList.size())
        {
            updatePolicyLayout();
        }

    }
    
    //action
    private HashMap<String, Object> makeMap(TAction action)
    {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("action", action);
        map.put("deleteListener", new ActionDeleteListener(this, action));
        map.put("listener", new ActionButtonListener(this, action));
        map.put("longListener", new ActionLongClickListener(this, action));
        map.put("childView", ActionMgr.getIntance().createChildView(this, action));
        map.put("parent", this);
        map.put("visibility", View.GONE);
        map.put("scrollview", this.mScrollView);
        
        return map;
    }
    
    private void updateActionLayout()
    {
        // 定时动作
        mActionList.clear();
        for (TAction action : mTimer.getTActions())
        {
            mActionList.add(this.makeMap(action));
        }

        mActionAdapter.notifyDataSetChanged();
    }
    
    private void updateActionLayout(TAction action, ChildView view)
    {
        int i = 0;
        for(; i < mActionList.size(); i++)
        {
            TAction a = (TAction) mActionList.get(i).get("action");
            if(a.getExecOrder() == action.getExecOrder())
            {
                mActionList.get(i).put("action", action);
                mActionList.get(i).put("childView", view);
                mActionAdapter.notifyDataSetChanged();
                return;
            }
        }
        
        if(i == mActionList.size())
        {
            updateActionLayout();
        }
    }

    private void updateActionLayout(TAction action)
    {
        int i = 0;
        for(; i < mActionList.size(); i++)
        {
            TAction a = (TAction) mActionList.get(i).get("action");
            if(a.getExecOrder() == action.getExecOrder())
            {
                mActionList.get(i).put("action", action);
                mActionAdapter.notifyDataSetChanged();
                return;
            }
        }
        
        if(i == mActionList.size())
        {
            updateActionLayout();
        }
    }

    private void updateLayout()
    {        
        updateTimerDefLayout();
        updatePolicyLayout();
        updateActionLayout();
    }

    //参数校验错误提示对话框
    private void displayValidDialog(String validInfo)
    {
        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle("错误");
        builder.setMessage(validInfo);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.create().show();
    }

    //参数校验错误提示对话框
    private void displayValidDialog(String title, String validInfo)
    {
        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle(title);
        builder.setMessage(validInfo);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.create().show();
    }

    private void stopAllActions()
    {
        //关闭所有动作子布局，停止所有动作
        for(int i = 0;i < mActionList.size(); i++)
        {
            mActionList.get(i).put("stop", 1);
        }
        mActionAdapter.notifyDataSetChanged();
    }

    private void registerListener()
    {
        // policy菜单 点击其他地方消失
        mPolicyMenuView.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if (mPolicyMenu != null && mPolicyMenu.isShowing())
                {
                    mPolicyMenu.dismiss();
                }
                return false;
            }

        });   
        //policy 菜单：包含、例外
        mPolicyMenuInclude.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                TLoopPolicy policy = mTimer.getLoopPolicys().get(mCurrentPolicyPos);
                int tmp = (policy.getExcludeFlag() == 0 ? 1 : 0);
                policy.setExcludeFlag(tmp);
                updatePolicyLayout(policy);
                
                mPolicyMenu.dismiss();
                mCurrentPolicyPos = -1;
            }
        });
        //policy 菜单：变更
        mPolicyMenuChange.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent i = new Intent(SettingActivityTimer.this, FragmentActivityAddLoopPolicy.class);
                startActivityForResult(i, REQUEST_CODE_LOOP_CHANGE);
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

                mPolicyMenu.dismiss();
            }
        });
        //policy 菜单：删除
        mPolicyMenuDelete.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                mTimer.getLoopPolicys().remove(mCurrentPolicyPos);
                mLoopPolicyList.remove(mCurrentPolicyPos);
                mLoopPolicyAdapter.notifyDataSetChanged();
                
                mPolicyMenu.dismiss();
                mCurrentPolicyPos = -1;
            }
        });
        
        // action 菜单 点击其他地方消失
        mActionMenuView.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if (mActionMenu != null && mActionMenu.isShowing())
                {
                    mActionMenu.dismiss();
                }
                return false;
            }

        });   
        //action 菜单：变更
        mActionMenuChange.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent i = new Intent(SettingActivityTimer.this, FragmentActivityAddAction.class);
                startActivityForResult(i, REQUEST_CODE_ACTION_CHANGE);
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

                mActionMenu.dismiss();
            }
        });
        //action 菜单：删除
        mActionMenuDelete.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                mTimer.getTActions().remove(mCurrentActionPos);
                mActionList.remove(mCurrentActionPos);
                mActionAdapter.notifyDataSetChanged();
                
                mActionMenu.dismiss();
                mCurrentActionPos = -1;
            }
        });
        
        // 新增循环策略
        mBtnAddLoopPolicy.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent i = new Intent(SettingActivityTimer.this, FragmentActivityAddLoopPolicy.class);
                startActivityForResult(i, REQUEST_CODE_LOOP_NEW);
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            }

        });
        // 新增循环策略
        mTvNoLoopPolicy.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent i = new Intent(SettingActivityTimer.this, FragmentActivityAddLoopPolicy.class);
                startActivityForResult(i, REQUEST_CODE_LOOP_NEW);
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            }

        });
        
        // 新增动作
        mBtnAddAction.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent i = new Intent(SettingActivityTimer.this, FragmentActivityAddAction.class);
                startActivityForResult(i, REQUEST_CODE_ACTION_NEW);
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            }

        });
        // 新增动作
        mTvNoAction.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent i = new Intent(SettingActivityTimer.this, FragmentActivityAddAction.class);
                startActivityForResult(i, REQUEST_CODE_ACTION_NEW);
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            }

        });
        

        // 保存
        mBtnSave.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View v)
            {                
                //关闭所有动作子布局，停止所有动作
                stopAllActions();
                
                //
                String errString = mTimer.getTimerDef().CheckValidity();
                if(errString != null)
                {
                    displayValidDialog("启动时刻设置错误",errString);
                    return;
                }
                
                //循环策略
                mTimer.getLoopPolicys().clear();
                int cnt = mLoopPolicyList.size();
                int excludeFlag = 1;
                for(int i = 0; i < cnt; i++)
                {
                    TLoopPolicy policy = (TLoopPolicy) mLoopPolicyList.get(i).get("policy");
                    errString = policy.CheckValidity();
                    if(errString != null)
                    {
                        displayValidDialog("第"+(i+1)+"个循环周期设置错误",errString);
                        return;
                    }
                    
                    mTimer.getLoopPolicys().add(policy);
                    
                    if(policy.getExcludeFlag() == 0)
                    {
                        excludeFlag = 0;
                    }
                }
                if(excludeFlag == 1)
                {
                    displayValidDialog("没有一个有效的循环策略");
                    return;
                }
                

                //定时动作
                mTimer.getTActions().clear();
                cnt = mActionList.size();
                if(cnt == 0)
                {
                    displayValidDialog("没有一个有效的定时动作");
                    return;
                }
                for(int i = 0; i < cnt; i++)
                {
                    TAction action = (TAction) mActionList.get(i).get("action");
                    mTimer.getTActions().add(action);
                }

                DBHelper.getIntance().updateTimer(mTimer);

                Intent i = new Intent();
                i.putExtra(TimerMgr.ALARM_INTENT_EXTRA, mTimer);
                setResult(RESULT_OK, i);
                finish();
            }
        });

        // 取消
        mBtnCancel.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View v)
            {
                stopAllActions();
                finish();
            }
        });

    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (RESULT_OK != resultCode)
        {
            return;
        }

        switch (requestCode)
        {
        //TimerDef设置
        case REQUEST_CODE_TIME_SETTING:
            TTimerDef timerDef = (TTimerDef) data.getSerializableExtra(TimerMgr.ALARM_INTENT_TIMER_DEF);
            if (timerDef != null)
            {
                mTimer.setTimerDef(timerDef);
                updateTimerDefLayout(timerDef);
            }
            break;
        //循环策略设置
        case REQUEST_CODE_LOOP_SETTING:
            TLoopPolicy policy = (TLoopPolicy) data.getSerializableExtra(TimerMgr.ALARM_INTENT_LOOP_POLICY);
            if (policy != null)
            {
                mTimer.setLoopPolicy(policy);
                Util.log("mTimer.setLoopPolicy: " + policy.getDisplayOrder());
                updatePolicyLayout(policy);
            }
            break;
        //新增循环策略
        case REQUEST_CODE_LOOP_NEW:
            TLoopPolicy policyNew = (TLoopPolicy) data.getSerializableExtra(TimerMgr.ALARM_INTENT_LOOP_POLICY);
            if (policyNew != null)
            {
                mTimer.setLoopPolicy(policyNew);
                HashMap<String, Object> map = this.makeMap(policyNew);
                map.put("visibility", View.VISIBLE);
                mLoopPolicyList.add(map);
                mLoopPolicyAdapter.notifyDataSetChanged(); 
                Util.log("mTimer.setNewLoopPolicy: " + policyNew.getDisplayOrder());
            }
            break;
        //变更循环策略
        case REQUEST_CODE_LOOP_CHANGE:
            TLoopPolicy changePolicy = (TLoopPolicy) data.getSerializableExtra(TimerMgr.ALARM_INTENT_LOOP_POLICY);
            if (changePolicy != null)
            {
                int seq = mTimer.getLoopPolicys().get(mCurrentPolicyPos).getDisplayOrder();
                changePolicy.setDisplayOrder(seq);
                
                mTimer.setLoopPolicy(changePolicy);
                updatePolicyLayout(changePolicy, createChildViewPolicy(changePolicy));
                Util.log("mTimer.changeLoopPolicy: " + changePolicy.getDisplayOrder());
            }
            mCurrentPolicyPos = -1;
            break;     
        //动作设置
        case REQUEST_CODE_ACTION_SETTING:
            TAction action = (TAction) data.getSerializableExtra(TimerMgr.ALARM_INTENT_ACTION);
            if (action != null)
            {
                mTimer.setAction(action);
                Util.log("mTimer.setAction[" + action.getExecOrder() + "]: param=" + action.getParam());
                updateActionLayout(action);
            }
            break;
        //新增动作
        case REQUEST_CODE_ACTION_NEW:
            TAction actionNew = (TAction) data.getSerializableExtra(TimerMgr.ALARM_INTENT_ACTION);
            if (actionNew != null)
            {
                mTimer.setAction(actionNew);
                HashMap<String, Object> map = this.makeMap(actionNew);
                map.put("visibility", View.VISIBLE);
                mActionList.add(map);
                mActionAdapter.notifyDataSetChanged(); 
                Util.log("mTimer.setNewAction[" + actionNew.getExecOrder() + "]: param=" + actionNew.getParam());
            }
            break;     
        //变更动作
        case REQUEST_CODE_ACTION_CHANGE:
            TAction changeAction = (TAction) data.getSerializableExtra(TimerMgr.ALARM_INTENT_ACTION);
            if (changeAction != null)
            {
                int seq = mTimer.getTActions().get(mCurrentActionPos).getExecOrder();
                changeAction.setExecOrder(seq);

                mTimer.setAction(changeAction);
                Util.log("mTimer.setAction[" + changeAction.getExecOrder() + "]: param=" + changeAction.getParam());
                updateActionLayout(changeAction, ActionMgr.getIntance().createChildView(this, changeAction));
            }
            mCurrentActionPos = -1;
            break;     
        default:
            break;
        }
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        StatService.onPause(this);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        StatService.onResume(this);
    }

    //////////////////////////////////////////////////////////////////
    //显示时间设置子布局
    class TimeDefButtonListener implements OnClickListener 
    {

        TimeDefButtonListener() 
        {
        }
        
        @Override
        public void onClick(View v) 
        {            
            if((Integer)mTimeDefList.get(0).get("visibility") == View.VISIBLE)
            {
                mTimeDefList.get(0).put("visibility", View.GONE);
            }
            else
            {
                mTimeDefList.get(0).put("visibility", View.VISIBLE);
            }

            mTimeDefAdapter.notifyDataSetChanged(); 
            
        }
    }
    
    //显示循环策略子布局
    class LoopPolicyButtonListener implements OnClickListener 
    {
        private TLoopPolicy mPolicy;
        @SuppressWarnings("unused")
        private Context mContext;

        LoopPolicyButtonListener(Context context, TLoopPolicy policy) 
        {
            mContext = context;
            mPolicy = policy;
        }
        
        public void setTag(Object o)
        {
            if(o instanceof TLoopPolicy)
            {
                mPolicy = (TLoopPolicy)o;
            }
        }

        @Override
        public void onClick(View v) 
        {
            Util.log("Click policy " + mPolicy.getPolicyType());
            for(int i = 0; i < mLoopPolicyList.size(); i++)
            {
                TLoopPolicy policy = (TLoopPolicy)mLoopPolicyList.get(i).get("policy");
                if(policy.getDisplayOrder() == mPolicy.getDisplayOrder())
                {
                    if((Integer)mLoopPolicyList.get(i).get("visibility") == View.VISIBLE)
                    {
                        mLoopPolicyList.get(i).put("visibility", View.GONE);
                    }
                    else
                    {
                        mLoopPolicyList.get(i).put("visibility", View.VISIBLE);
                    }
                }
                else
                {
                    mLoopPolicyList.get(i).put("visibility", View.GONE);
                }
            }
            mLoopPolicyAdapter.notifyDataSetChanged(); 
        }
    }
    
    //长按循环策略
    class LoopPolicyLongClickListener implements OnLongClickListener 
    {
        private TLoopPolicy mPolicy;
        private Context mContext;

        LoopPolicyLongClickListener(Context context, TLoopPolicy policy) 
        {
            mContext = context;
            mPolicy = policy;
        }
        
        public void setTag(Object o)
        {
            if(o instanceof TLoopPolicy)
            {
                mPolicy = (TLoopPolicy)o;
            }
        }

        @Override
        public boolean onLongClick(View v)
        {
            Util.log("Long Click policy " + mPolicy.getPolicyType());
                        
            for(int i = 0; i < mLoopPolicyList.size(); i++)
            {
                TLoopPolicy policy = (TLoopPolicy)mLoopPolicyList.get(i).get("policy");
                if(policy.getDisplayOrder() == mPolicy.getDisplayOrder())
                {
                    mCurrentPolicyPos = i;
                    if(policy.getExcludeFlag() == 0)
                    {
                        mPolicyMenuInclude.setText(mContext.getString(R.string.policy_menu_exclude));
                    }
                    else
                    {
                        mPolicyMenuInclude.setText(mContext.getString(R.string.policy_menu_include));
                    }
                                        
                    //anchor Bottom
                    int[] location = new  int[2] ;
                    v.getLocationOnScreen(location);
                    int anchorBottom = location[1] + v.getHeight();
                    //分辨率
                    int displayBottom = getResources().getDisplayMetrics().heightPixels;
                    
                    int offset = anchorBottom + mPolicyMenuHeight - displayBottom;
                    Util.log("offset: " + offset + "=" + anchorBottom + "+" + mPolicyMenuHeight + "-" + displayBottom);
                    if(offset > 0)
                    {
                        mPolicyMenu.showAsDropDown(v, 0, -offset);
                    }
                    else
                    {
                        mPolicyMenu.showAsDropDown(v);
                    }
                    
                    return true;
                }
            }
            
            return false;
        }
    }

    //删除循环策略
    class LoopPolicyDeleteListener implements OnClickListener 
    {
        private TLoopPolicy mPolicy;
        @SuppressWarnings("unused")
        private Context mContext;

        LoopPolicyDeleteListener(Context context, TLoopPolicy policy) 
        {
            mContext = context;
            mPolicy = policy;
        }
        
        public void setTag(Object o)
        {
            if(o instanceof TLoopPolicy)
            {
                mPolicy = (TLoopPolicy)o;
            }
        }

        @Override
        public void onClick(View v) 
        {
            Util.log("delete policy: " + mPolicy.getDisplayOrder() + ": " + mPolicy.toString());

            Vector<TLoopPolicy> policyArray = mTimer.getLoopPolicys();
            for(int i = 0; i < policyArray.size(); i++)
            {
                if(policyArray.get(i).getDisplayOrder() == mPolicy.getDisplayOrder())
                {
                    policyArray.remove(i);
                    break;
                }
            }
            
            for(int i = 0; i < mLoopPolicyList.size(); i++)
            {
                TLoopPolicy policy = (TLoopPolicy) mLoopPolicyList.get(i).get("policy");
                if(policy.getDisplayOrder() == mPolicy.getDisplayOrder())
                {
                    mLoopPolicyList.remove(i);
                    break;
                }
            }

            mLoopPolicyAdapter.notifyDataSetChanged(); 
        }
    }

    //显示动作子布局
    class ActionButtonListener implements OnClickListener 
    {
        protected TAction mAction;
        protected Context mContext;

        ActionButtonListener(Context context, TAction action) 
        {
            mContext = context;
            mAction = action;
        }
        
        public void setTag(Object o)
        {
            if(o instanceof TAction)
            {
                mAction = (TAction)o;
            }
        }
        
        public boolean willNewActivity()
        {
            if(ActionMgr.ACTION_KLAXON.equals(mAction.getActionType())
                    || ActionMgr.ACTION_PHONE.equals(mAction.getActionType()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        @Override
        public void onClick(View v) 
        {
            for(int i = 0; i < mActionList.size(); i++)
            {
                TAction action = (TAction)mActionList.get(i).get("action");
                if(action.getExecOrder() == mAction.getExecOrder())
                {
                    //闹铃
                    if(ActionMgr.ACTION_KLAXON.equals(action.getActionType())
                            && (ChildView) mActionList.get(i).get("childView") == null)
                    {
                        Intent intent = new Intent(mContext, MusicBrowserActivity.class);
                        intent.putExtra(TimerMgr.ALARM_INTENT_ACTION, mAction);
                        SettingActivityTimer.this.startActivityForResult(intent, 
                                SettingActivityTimer.REQUEST_CODE_ACTION_SETTING);
                    }
                    //拨打电话
                    else if(ActionMgr.ACTION_PHONE.equals(action.getActionType())
                            && (ChildView) mActionList.get(i).get("childView") == null)
                    {
                        Intent intent = new Intent(mContext,SelectContactsActivity.class);
                        intent.putExtra(TimerMgr.ALARM_INTENT_ACTION, mAction);
                        intent.putExtra(TimerMgr.ALARM_INTENT_EXTRA, 1);
                        SettingActivityTimer.this.startActivityForResult(intent, 
                                SettingActivityTimer.REQUEST_CODE_ACTION_SETTING);
                    }
                    //没有配置参数
                    else if((ChildView) mActionList.get(i).get("childView") == null)
                    {
                        Toast.makeText(SettingActivityTimer.this, "没有配置参数", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    //有子布局的情况
                    if((Integer)mActionList.get(i).get("visibility") == View.VISIBLE)
                    {
                        mActionList.get(i).put("visibility", View.GONE);
                    }
                    else
                    {
                        mActionList.get(i).put("visibility", View.VISIBLE);
                    }
                }
                else
                {
                    mActionList.get(i).put("visibility", View.GONE);
                }
            }
            mActionAdapter.notifyDataSetChanged(); 
        }
    }
    
    //长按动作
    class ActionLongClickListener implements OnLongClickListener 
    {
        private TAction mAction;
        @SuppressWarnings("unused")
        private Context mContext;

        ActionLongClickListener(Context context, TAction action) 
        {
            mContext = context;
            mAction = action;
        }
        
        public void setTag(Object o)
        {
            if(o instanceof TAction)
            {
                mAction = (TAction)o;
            }
        }

        @Override
        public boolean onLongClick(View v)
        {
            Util.log("Long Click policy " + mAction.getActionType());
                        
            for(int i = 0; i < mActionList.size(); i++)
            {
                TAction action = (TAction)mActionList.get(i).get("action");
                if(action.getExecOrder() == mAction.getExecOrder())
                {
                    mCurrentActionPos = i;
                    
                    //anchor Bottom
                    int[] location = new  int[2] ;
                    v.getLocationOnScreen(location);
                    int anchorBottom = location[1] + v.getHeight();
                    //分辨率
                    int displayBottom = getResources().getDisplayMetrics().heightPixels;
                    
                    int offset = anchorBottom + mActionMenuHeight - displayBottom;
                    Util.log("offset: " + offset + "=" + anchorBottom + "+" + mActionMenuHeight + "-" + displayBottom);
                    if(offset > 0)
                    {
                        mActionMenu.showAsDropDown(v, 0, -offset);
                    }
                    else
                    {
                        mActionMenu.showAsDropDown(v);
                    }

                    return true;
                }
            }
            
            return false;
        }
    }

    //删除动作
    class ActionDeleteListener implements OnClickListener 
    {
        private TAction mAction;
        @SuppressWarnings("unused")
        private Context mContext;

        ActionDeleteListener(Context context, TAction action) 
        {
            mContext = context;
            mAction = action;
        }
        
        public void setTag(Object o)
        {
            if(o instanceof TAction)
            {
                mAction = (TAction)o;
            }
        }
        
        @Override
        public void onClick(View v) 
        {
            Util.log("delete policy " + mAction.getDescription() + ": " + mAction.toString());

            Vector<TAction> actionArray = mTimer.getTActions();
            for(int i = 0; i < actionArray.size(); i++)
            {
                if(actionArray.get(i).getExecOrder() == mAction.getExecOrder())
                {
                    actionArray.remove(i);
                    break;
                }
            }
            
            for(int i = 0; i < mActionList.size(); i++)
            {
                TAction action = (TAction) mActionList.get(i).get("action");
                if(action.getExecOrder() == mAction.getExecOrder())
                {
                    mActionList.remove(i);
                    break;
                }
            }


            mActionAdapter.notifyDataSetChanged(); 
        }
    }

    @Override
    public void dataUpdateNotify()
    {
        // TODO Auto-generated method stub
        
    }
}
